package com.hq.door.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.sql.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.hq.door.dao.TOutRequestDAO;
import com.hq.door.dao.TRecordsDAO;
import com.hq.door.dao.TStudentDAO;
import com.hq.door.dao.TTeacherDAO;
import com.hq.door.dto.OutRequestDto;
import com.hq.door.dto.OutrequestInfo;
import com.hq.door.dto.Pagination;
import com.hq.door.dto.Parent;
import com.hq.door.dto.ParentApplyFront;
import com.hq.door.dto.ParentRecordFront;
import com.hq.door.dto.StudentInfo;
import com.hq.door.dto.TRecordInfo;
import com.hq.door.dto.Teacher;
import com.hq.door.dto.TeacherDto;
import com.hq.door.pojo.TOutRequest;
import com.hq.door.pojo.TParent;
import com.hq.door.pojo.TRecords;
import com.hq.door.pojo.TStudent;
import com.hq.door.pojo.TTeacher;
import com.hq.door.service.TTeacherService;
import com.hq.door.util.ExcelUtil;

/**
 * <p>
 * Title: TeacherServiceImpl
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author jevons
 * @date 2017年3月4日 下午1:51:59
 */
@Service("tTeacherService")
public class TeacherServiceImpl extends BaseServiceImpl<TTeacher> implements
		TTeacherService {
	@Autowired
	TTeacherDAO tTeacherDAO;
	TRecordsDAO recordDao;
	TOutRequestDAO outRequestDao;
	TStudentDAO tStudentDAO;

	public TRecordsDAO getRecordDao() {
		return recordDao;
	}

	@Autowired
	public void setRecordDao(TRecordsDAO recordDao) {
		this.recordDao = recordDao;
	}

	public TOutRequestDAO getOutRequestDao() {
		return outRequestDao;
	}

	@Autowired
	public void setOutRequestDao(TOutRequestDAO outRequestDao) {
		this.outRequestDao = outRequestDao;
	}

	public TStudentDAO gettStudentDAO() {
		return tStudentDAO;
	}

	@Autowired
	public void settStudentDAO(TStudentDAO tStudentDAO) {
		this.tStudentDAO = tStudentDAO;
	}

	public TTeacherDAO gettTeacherDAO() {
		return tTeacherDAO;
	}

	@Autowired
	public void settTeacherDAO(TTeacherDAO tTeacherDAO) {
		this.tTeacherDAO = tTeacherDAO;
		this.setBaseDao(tTeacherDAO);
	}

	/**
	 * 前台家长端登录检查
	 */
	@Override
	public TTeacher check(String userName, String password) {
		TTeacher tTeacher = null;// inner join fetch t.TClass c inner join fetch
									// c.TStudent s
		StringBuffer hql = new StringBuffer(
				"from TTeacher t inner join fetch t.TClass tc where t.account = ? and t.password = ?");
		tTeacher = tTeacherDAO.queryOne(hql.toString(), userName, password);
		return tTeacher;
	}

	/**
	 * 前台家长端微信登录
	 * 
	 * @param wexinId
	 * @return
	 */
	public TTeacher wxLogin(String weixinId) {
		String hql = "from TTeacher t inner join fetch t.TClass c where t.weixinId=?";
		TTeacher tTeacher = tTeacherDAO.queryOne(hql, weixinId);
		return tTeacher;
	}

	/**
	 * 修改一条教师信息 添加微信id
	 */
	@Override
	public TTeacher modifyTeacher(String name, String password, String weixinId) {
		TTeacher tTeacher = null;
		StringBuffer hql = new StringBuffer(
				"from TTeacher t inner join fetch t.TClass c where t.account=? and t.password=?");
		tTeacher = tTeacherDAO.queryOne(hql.toString(), name, password);
		if (tTeacher != null) {
			tTeacher.setWeixinId(weixinId);
			tTeacherDAO.update(tTeacher);
		}
		return tTeacher;
	}

	/**
	 * 根据老师查询 对应学生的刷卡记录
	 */
	public Pagination queryRecordsByTeacher(TTeacher tTeacher,
			ParentRecordFront prf) {
		StringBuffer hql = null;
		StringBuffer hqlCount = null;
		StringBuffer hqlWhere = null;
		List<Object> conditions = null;
		String stuName = "";
		// 2.使用学生的卡号（不是学号）
		hql = new StringBuffer(
				"select r,ts from TRecords r,TStudent ts inner join ts.TClass tc inner join tc.TTeacher tt");
		hqlCount = new StringBuffer(
				"select count(r.id) from TRecords r,TStudent ts inner join ts.TClass tc inner join tc.TTeacher tt");
		hqlWhere = new StringBuffer(" where 1=1");
		conditions = new ArrayList<Object>();
		if (tTeacher.getId() != null) {
			/*
			 * String cardNo = tparent.getTStudent().getCordNo(); stuName =
			 * tparent.getTStudent().getName(); conditions.add(cardNo);
			 * for(Object obj : conditions){ hqlWhere.append(
			 * " and r.cardNo in (select s.cardNo from TStudent s inner join fetch TClass c where c.id="
			 * ++")"); }
			 */
			hqlWhere.append(" and r.cardNo=ts.cordNo and tt.id="
					+ tTeacher.getId());
			if ("2".equals(prf.getType())) {// 进校
				hqlWhere.append(" and r.inoutType=0 and r.isException=0");
			}
			if ("1".equals(prf.getType())) {// 出校
				hqlWhere.append(" and r.inoutType=1 and r.isException=0");
			}
			if ("3".equals(prf.getType())) {// 异常出入
				hqlWhere.append(" and r.isException=1");
			}
			if (!"".equals(prf.getStuName())) {
				conditions.add("%" + prf.getStuName() + "%");
				hqlWhere.append(" and ts.name like ?");
			}
			conditions.add(prf.getStartDate());
			conditions.add(prf.getEndDate());
			hqlWhere.append(" and r.createTime>? and r.createTime<?");
		} else {
			hqlWhere.append(" and 1=0");
		}
		hqlWhere.append(" order by r.createTime desc");
		System.out.println(prf.getPageSize());
		System.out.println(prf.getPageNo());
		Integer pageStart = prf.getPageSize() * (prf.getPageNo() - 1);
		hql.append(hqlWhere);
		hqlCount.append(hqlWhere);
		List<Object[]> resList = outRequestDao.findPageObjects(hql.toString(),
				pageStart, prf.getPageSize(), conditions.toArray());
		List<TRecordInfo> tRecordList = new ArrayList<TRecordInfo>();
		Integer itemCount = outRequestDao.getCount(hqlCount.toString(),
				conditions.toArray());
		for (Object[] objs : resList) {
			TRecords tRecords = (TRecords) objs[0];
			TStudent tStudent = (TStudent) objs[1];
			TRecordInfo info = new TRecordInfo();
			info.getTRecord(tRecords);
			info.setStudentName(tStudent.getName());
			tRecordList.add(info);
		}
		Pagination pagination = new Pagination(itemCount, "", tRecordList);
		return pagination;
	}

	/**
	 * 根据条件查询所有学生的外出申请记录
	 * */

	public Pagination queryAllApplys(int type, String[] para, int pageSize,
			int pageNo) {
		StringBuffer hql = null;
		StringBuffer hqlCount = null;
		List<String> conditions = new ArrayList<String>();
		hql = new StringBuffer(
				"select o from TOutRequest o inner join fetch o.TStudent s inner join fetch s.TClass c inner join fetch c.TMajor m inner join fetch m.TInstitute ins where o.authStatus=0");

		hqlCount = new StringBuffer(
				"select count(o.id) from TOutRequest o inner join o.TStudent s inner join s.TClass c inner join c.TMajor m inner join m.TInstitute ins where o.authStatus=0");

		int pageStart = pageSize * (pageNo - 1);

		System.out.println(para);

		for (int i = 0; i < para.length; i++) {
			if (!"".equals(para[i])) {
				hql = hql.append(" and");
				hqlCount = hqlCount.append(" and");
				switch (i) {
				case 0:
					hql = hql.append(" ins.name=?");
					hqlCount = hqlCount.append(" ins.name=?");
					conditions.add(para[i]);
					break;
				case 1:
					hql = hql.append(" m.name=?");
					hqlCount = hqlCount.append(" m.name=?");
					conditions.add(para[i]);
					break;
				case 2:
					hql = hql.append(" c.name=?");
					hqlCount = hqlCount.append(" c.name=?");
					conditions.add(para[i]);
					break;
				case 3:
					hql = hql.append(" c.grade=?");
					hqlCount = hqlCount.append(" c.grade=?");
					conditions.add(para[i]);
					break;
				default:
					break;
				}
			}
		}

		List<TOutRequest> toutRequestList = outRequestDao.findPageObjects(
				hql.toString(), pageStart, pageSize, conditions.toArray());
		Integer itemCount = outRequestDao.getCount(hqlCount.toString(),
				conditions.toArray());
		List<OutrequestInfo> resultList = new OutrequestInfo()
				.getTOutrequest(toutRequestList);
		Pagination pagination = new Pagination(itemCount, "", resultList);

		return pagination;
	}

	/**
	 * 根据老师查询 对应学生的申请记录
	 */
	public Pagination queryApplysByTeacher(TTeacher tTeacher,
			ParentApplyFront paf) {
		StringBuffer hql = null;
		StringBuffer hqlCount = null;
		StringBuffer hqlWhere = null;
		List<Object> conditions = null;
		// 2.把学生id拼成参数，考虑多个学生id情况
		hqlWhere = new StringBuffer(" where 1=1");
		conditions = new ArrayList<Object>();
		if (tTeacher != null && tTeacher.getTClass() != null) {
			if (paf.getType() != null) {
				if ("4".equals(paf.getType())) {
					hqlWhere.append(" and o.authStatus<>0");
				} else {
					hqlWhere.append(" and o.authStatus=?");
					conditions.add(Integer.valueOf(paf.getType()));
				}

			}
			if (!"".equals(paf.getStuName())) {
				conditions.add("%" + paf.getStuName() + "%");
				hqlWhere.append(" and s.name like ?");
			}
			if (paf.getStartDate() != null) {
				conditions.add(paf.getStartDate());
				hqlWhere.append(" and o.startTime>=?");
			}
			if (paf.getEndDate() != null) {
				conditions.add(paf.getEndDate());
				hqlWhere.append(" and o.endTime <=?");
			}
			hqlWhere.append(" and t.id=?");
			conditions.add(tTeacher.getId());
		} else {
			hqlWhere.append(" and 1=0");
		}
		hqlWhere.append(" order by o.startTime desc");
		hql = new StringBuffer(
				"select o from TOutRequest o inner join fetch o.TStudent s")
				.append(" inner join fetch s.TClass c inner join fetch c.TMajor inner join fetch o.TTeacher t");
		hqlCount = new StringBuffer(
				"select count(o.id) from TOutRequest o inner join o.TStudent s inner join o.TTeacher t");
		Integer pageStart = paf.getPageSize() * (paf.getPageNo() - 1);
		hql.append(hqlWhere);
		hqlCount.append(hqlWhere);
		List<TOutRequest> toutRequestList = outRequestDao.findPageObjects(
				hql.toString(), pageStart, paf.getPageSize(),
				conditions.toArray());
		Integer itemCount = outRequestDao.getCount(hqlCount.toString(),
				conditions.toArray());
		List<OutrequestInfo> resultList = new OutrequestInfo()
				.getTOutrequest(toutRequestList);
		Pagination pagination = new Pagination(itemCount, "", resultList);
		return pagination;
	}

	@Override
	public int updateApproveList(List<OutrequestInfo> infos) {
		int res = 0;
		String hql = "select tor from TOutRequest tor where authStatus=0 and tor.id=?";
		for (OutrequestInfo info : infos) {
			TOutRequest tOutRequest = outRequestDao.queryOne(hql, info.getId());
			if (tOutRequest != null) {
				tOutRequest.setAuthStatus(info.getAuthStatus());
				tOutRequest.setRejectReason(info.getRejectReason());
				tOutRequest.setAuthTime(new Timestamp(System
						.currentTimeMillis()));
				outRequestDao.update(tOutRequest);
				res++;
			}
		}
		return res;
	}

	@Override
	public OutrequestInfo getOneApply(Integer id) {
		// TODO Auto-generated method stub
		TOutRequest res = outRequestDao.get(id);

		OutrequestInfo info = new OutrequestInfo();
		info.getRequestInfo(res);

		return info;
	}

	@Override
	public int saveReplaceList(List<OutrequestInfo> infos, TTeacher teacher) {
		int res = 0;
		for (OutrequestInfo Info : infos) {
			String hql = "select ts from TStudent ts where ts.code=?";
			TStudent tStudent = tStudentDAO
					.queryOne(hql, Info.getStudentname());
			if (tStudent != null) {
				TOutRequest request = new TOutRequest();
				request.setAuthStatus(1);
				request.setStartTime(Info.getStartTime());
				request.setEndTime(Info.getEndTime());
				request.setAuthTime(new Timestamp(System.currentTimeMillis()));
				request.setRequestTime(new Timestamp(System.currentTimeMillis()));
				request.setIsAgent(1);
				request.setRequestReason(Info.getRequestReason());
				request.setTStudent(tStudent);
				request.setTTeacher(teacher);
				outRequestDao.save(request);
				res++;
			}
		}

		return res;
	}

	@Override
	public Pagination getCurTeaStus(TTeacher tTeacher, Integer pageNo,
			Integer pageSize) {
		StringBuffer hql = null;
		StringBuffer hqlCount = null;
		StringBuffer hqlWhere = null;

		hql = new StringBuffer(
				"select ts from TStudent ts inner join ts.TClass tc inner join tc.TTeacher tt");
		hqlCount = new StringBuffer(
				"select count(ts.id) from TStudent ts inner join ts.TClass tc inner join tc.TTeacher tt");
		hqlWhere = new StringBuffer(" where tt.id=?");
		hql.append(hqlWhere);
		hqlCount.append(hqlWhere);

		List<StudentInfo> Infos = new ArrayList<StudentInfo>();
		List<TStudent> students = new ArrayList<TStudent>();
		int itemCount = 0;
		Integer pageStart = pageSize * (pageNo - 1);
		students = tStudentDAO.findPageObjects(hql.toString(), pageStart,
				pageSize, tTeacher.getId());
		itemCount = tStudentDAO.getCount(hqlCount.toString(), tTeacher.getId());
		Infos = new StudentInfo().getStudentByPage(students);

		Pagination pagination = new Pagination(itemCount, "", Infos);

		return pagination;
	}

	/**
	 * 批量导入教师信息
	 * 
	 * @param list
	 * @return
	 */
	public String addTeacherList(List<Map<String, String>> list) {
		List<TeacherDto> dtos = data2Dtos(list);
		Integer result = 0;
		TeacherDto dto = null;
		String hql = "";
		for (int index = 0; dtos != null && index < dtos.size(); index++) {
			dto = dtos.get(index);
			TTeacher tt = TeacherDto.readTeacher(dto);
			// 检测是否存在该帐户
			hql = "select t from TTeacher t  where t.account = ? order by t.modifiedTime desc";
			String para = tt.getAccount();
			List<Object> queryList = tTeacherDAO.queryList(hql, para);

			if (queryList.size() != 0) {
				return "导入失败，服务器中已存在帐号为 " + tt.getAccount() + " 的用户！请修改后重新提交！";
			}
			tTeacherDAO.save(tt);
			result++;
		}
		return "成功导入数据" + result + "条！";
	}

	/**
	 * Excel表中数据转dto
	 * 
	 * @param list
	 * @return
	 */
	public static List<TeacherDto> data2Dtos(List<Map<String, String>> list) {
		List<TeacherDto> dtos = new ArrayList<TeacherDto>();
		TeacherDto dto = null;
		for (int index = 0; list != null && index < list.size(); index++) {
			Map<String, String> map = list.get(index);
			dto = new TeacherDto(map.get(ExcelUtil.TNAME),
					map.get(ExcelUtil.TACCOUNT), map.get(ExcelUtil.TPASSWORD),
					map.get(ExcelUtil.TCODE), map.get(ExcelUtil.TMOBILE), false);
			dtos.add(dto);
		}
		return dtos;
	}

	// -------------------------------------------
	@Override
	public boolean deleteselect(int[] id) {
		TTeacher tTeacher = new TTeacher();
		for (int i = 0; i < id.length; i++) {
			tTeacher = tTeacherDAO.get(id[i]);
			if (tTeacher != null) {

				tTeacherDAO.delete(tTeacher);
			}
		}
		return true;
	}

	@Override
	public boolean updateselect(Teacher teacher) {
		String hql = "from TTeacher t where t.code=?";
		TTeacher tTeacher = tTeacherDAO.queryOne(hql, teacher.getCode());
		return false;
	}

	@Override
	public int getCount(int type, String para) {
		String hql;
		int count;
		switch (type) {
		case 0:
			hql = "select count(t.id) from TTeacher t";
			count = tTeacherDAO.getCount(hql);
			break;
		case 1:
			hql = "select count(t.id) from TTeacher t where t.code like ?";
			para = "%" + para + "%";
			count = tTeacherDAO.getCount(hql, para);
		case 2:
			hql = "select count(t.id) from TTeacher t where t.name like ?";
			para = "%" + para + "%";
			count = tTeacherDAO.getCount(hql, para);
		default:
			return 0;
		}
		return count;
	}

	@Override
	public Pagination getByPage(int type, String para, int pageStart,
			int pageSize) {
		Pagination pagination = null;
		String hql;
		List<Teacher> teachers = null;
		List<TTeacher> tTeachers = null;
		pageStart = (pageStart - 1) * pageSize;
		switch (type) {
		case 0:// 查询所有教师信息
			pagination = new Pagination();
			hql = "select t from TTeacher t order by t.modifiedTime desc";
			tTeachers = tTeacherDAO.findPageObjects(hql, pageStart, pageSize);
			Teacher[] tes = TeacherDto.writeMajor(tTeachers);
			teachers = new ArrayList<Teacher>();
			for (int i = 0; i < tes.length; i++) {
				teachers.add(tes[i]);
			}
			pagination.setList(TeacherDto.writeTeacher(tTeachers));
			break;
		case 1:// 按编号查询教师信息
			pagination = new Pagination();
			hql = "select t from TTeacher t where t.code like ? order by t.modifiedTime desc";
			para = "%" + para + "%";
			tTeachers = tTeacherDAO.findPageObjects(hql, pageStart, pageSize,
					para);
			Teacher[] tt1 = TeacherDto.writeMajor(tTeachers);
			teachers = new ArrayList<Teacher>();
			for (int i = 0; i < tt1.length; i++) {
				teachers.add(tt1[i]);
			}
			pagination.setList(TeacherDto.writeTeacher(tTeachers));
			break;
		case 2:// 按姓名查询教师信息
			pagination = new Pagination();
			hql = "select t from TTeacher t where t.name like ? order by t.modifiedTime desc";
			para = "%" + para + "%";
			tTeachers = tTeacherDAO.findPageObjects(hql, pageStart, pageSize,
					para);
			Teacher[] tt2 = TeacherDto.writeMajor(tTeachers);
			teachers = new ArrayList<Teacher>();
			for (int i = 0; i < tt2.length; i++) {
				teachers.add(tt2[i]);
			}
			pagination.setList(TeacherDto.writeTeacher(tTeachers));
			break;
		default:
			return pagination;
		}
		return pagination;
	}

	@Override
	public List<String> getTeacher() {
		List<String> teachernames = new ArrayList<String>();
		String hql = "select t from TClass c right join c.TTeacher t where c.name is null";
		Object[] values = {};
		List<TTeacher> list = tTeacherDAO.find(hql, values);
		for (int i = 0; i < list.size(); i++) {
			teachernames.add(list.get(i).getName());
		}
		return teachernames;
	}

	@Override
	public int updateTeaPassWord(String account, String passWord) {
		String hql = "from TTeacher where account=?";
		TTeacher tTeacher = tTeacherDAO.queryOne(hql, account);
		if (tTeacher != null) {
			tTeacher.setPassword(passWord);
			tTeacherDAO.update(tTeacher);
			return 0;
		} else {
			return 1;
		}
	}

	@Override
	public int modifyTeacherInfo(TTeacher tt) {
		List<Object> conditions = new ArrayList<>();
		;
		StringBuffer hql = new StringBuffer(
				"update  TTeacher set name =? ,mobile =?,code=?,modifiedBy=?");
		conditions.add(tt.getName());
		conditions.add(tt.getMobile());
		conditions.add(tt.getCode());
		conditions.add(tt.getModifiedBy());
		// -------------------------------------------------------
		// 假如需要在编辑模块更新账号信息，则启用本段代码；
		// if (tt.getAccount() != null && !tt.getAccount().equals("")) {
		// hql.append(",account=?");
		// conditions.add(tt.getAccount());
		// }
		// -------------------------------------------------------
		hql.append("  where id=?");
		conditions.add(tt.getId());
		return tTeacherDAO.modifyTeacherInfo(hql.toString(),
				conditions.toArray());
	}

	/**
	 * Description:单个教师账号查重
	 * @param tt
	 * @return true : 存在；false ：不存在。
	 * @see com.hq.door.service.TTeacherService#checkRepeatOfTeacherAccount(com.hq.door.pojo.TTeacher)
	 */
	@Override
	public boolean checkRepeatOfTeacherAccount(TTeacher tt) {
		// 检测是否存在该帐户
		String hql = "select t from TTeacher t  where t.account = ?";
		String para = tt.getAccount();
		List<Object> queryList = tTeacherDAO.queryList(hql, para);

		if (queryList.size() != 0) {
			return true;
		}
		return false;
	}

}
